# -*-coding: Utf-8 -*-
# @File : common .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time：2023/6/19
import random
import hashlib
from db import db_hander
from core import src


def get_bank_code():
    random_number_small = str(random.randint(1, 9))
    random_number_big = str(random.randint(1, 9))

    code = '1314521'
    for i in range(1, 3):
        code += random.choice([random_number_big, random_number_small])
    return code


def get_verify_code(n):
    random_number = str(random.randint(1, 10))
    random_eng_big = str(chr(random.randint(65, 90)))
    random_eng_small = str(chr(random.randint(97, 122)))
    code_temp = ''
    for i in range(1, n + 1):
        code_temp += random.choice([random_eng_big, random_eng_small, random_number])

    return code_temp


def encrypt_data(password, salt):
    md5 = hashlib.md5()

    data = password + salt

    md5.update(data.encode('utf8'))

    return md5.hexdigest()




def login_common(username, password, login_code, login_code_input, roles):
    if roles == 'user':
        data_dict = db_hander.select(username=username, roles='user')
    elif roles == 'admin':
        data_dict = db_hander.select(username=username, roles='admin')
    else:
        flow = f'请先进行身份验证!'
        return False, flow
    if not data_dict:
        flow = f'当前用户 :>>>{username} 不存在,请先注册!!'
        return False, flow
    encrypt_password = data_dict['password']
    salt = data_dict['salt']
    encrypt_password_now = encrypt_data(salt=salt, password=password)
    if encrypt_password == encrypt_password_now and login_code.upper() == login_code_input.upper():
        flow = f'登陆成功!!欢迎{username} 回家!'
        return True, flow
    else:
        flow = f'验证失败!!请再次确认你的用户名和密码!!'
        return False, flow


def login_auth(roles):
    def login(func_name):
        def inner(*args, **kwargs):

            if roles == 'user':
                if src.user.login_dict['username']:
                    res = func_name(*args, **kwargs)
                    return res
                else:
                    src.user.login()
            elif roles == 'admin':
                if src.admin.login_dict['username']:
                    res = func_name(*args, **kwargs)
                    return res
                else:
                    src.admin.login()
            else:
                print('无效的身份验证')

        return inner

    return login


if __name__ == '__main__':
    # code = get_verify_code(6)
    # print(code)
    # s = encrypt_data('1', 'q')
    code = get_bank_code()
    print(code)
